<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 奖罚详情 -->
    <div
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 项目信息 -->
        <a-card
          :bordered="false"
          class="mb20"
        >
          <title-name title="项目信息" />
          <a-form-model
            ref="ruleForm"
            :model="projectInfo"
            :rules="editModel == 2 ? {} : rules"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-row>
              <a-col :span="16">
                <a-form-model-item
                  label="奖罚单位"
                  prop="projectId"
                >
                  <org-tree-select
                    v-model="projectInfo.projectId"
                    :is-auto-select-first="editModel == 0"
                    :is-query-projec-detail="false"
                    is-need-auth
                    isAllowNnect
                    :needTags="['PD', 'CO', 'BC']"
                    :disabled="editModel == 2"
                    @select="selectOrg"
                    @handleChange="changeOrg"
                  />
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item-->
              <!--                  label="分公司"-->
              <!--                  prop="branchCompanyId"-->
              <!--                >-->
              <!--                  <select-sub-company-->
              <!--                    v-model="projectInfo.branchCompanyId"-->
              <!--                    placeholder="请选择"-->
              <!--                    :auto-selected="editModel == 0"-->
              <!--                    :disabled="editModel == 2"-->
              <!--                  />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item-->
              <!--                  label="项目名称"-->
              <!--                  prop="projectId"-->
              <!--                >-->
              <!--                  <select-project-->
              <!--                    v-model="projectInfo.projectId"-->
              <!--                    :is-clear="false"-->
              <!--                    placeholder="请选择"-->
              <!--                    :auto-selected="editModel == 0"-->
              <!--                    :disabled="editModel == 2"-->
              <!--                    :form="projectInfo"-->
              <!--                  />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
            </a-row>
          </a-form-model>
        </a-card>
        <!-- 奖罚信息 -->
        <a-card
          :bordered="false"
          :style="[{ marginBottom: editModel != 2 ? '50px' : '20px' }]"
        >
          <title-name title="奖罚信息" />
          <a-form-model
            ref="experimentForm"
            :model="rewardAndPenalty"
            :rules="editModel == 2 ? {} : rules"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="奖罚金额"
                  prop="rewardAndPenaltyAmount"
                >
                  <BaseInputNumber
                    v-model="rewardAndPenalty.rewardAndPenaltyAmount"
                    :min="0"
                    :max="1000000000000"
                    :formatter="(value) => `${value}元`"
                    :parser="(value) => value.replace('元', '')"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                    :precision="2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="奖罚类别"
                  prop="rewardAndPenaltyCategory"
                >
                  <selector
                    v-model="rewardAndPenalty.rewardAndPenaltyCategory"
                    placeholder="请选择"
                    :disabled="editModel == 2"
                    select-type="9"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="奖罚目标类别"
                  prop="rewardAndPenaltyTargetCategory"
                >
                  <selector
                    v-model="rewardAndPenalty.rewardAndPenaltyTargetCategory"
                    placeholder="请选择"
                    :disabled="editModel == 2 || (selectTageCode !== '' && selectTageCode !== 'PD')"
                    select-type="10"
                    @getList="getTargetCategoryList"
                    @onChange="handleChange"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="奖罚目标名称"
                  prop="rewardAndPenaltyTargetId"
                >
                  <a-auto-complete
                    v-model="rewardAndPenalty.rewardAndPenaltyTargetId"
                    :disabled="editModel == 2"
                    :placeholder="selectPlaceholder"
                    :data-source="targetNameArr"
                    allowClear
                    :filter-option="TargetNameFilterOption"
                    @select="TargetNameSelect"
                    @change="TargetNameChange"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="($currentPost().code === 'CO' || $currentPost().code === 'BC') && rewardAndPenalty.rewardAndPenaltyCategory === '621151584650399744'"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="8"
              >
                <a-form-model-item
                  label="是否纳入质量月报"
                  prop="subProject"
                  style="padding-left: 35px;"
                >
                  <a-switch
                    v-model="rewardAndPenalty.monthReportValue"
                    style="margin-top: -3px"
                    checked-children="on"
                    un-checked-children="off"
                    :disabled="editModel == 2"
                    @change="
                      (e) => {
                        rewardAndPenalty.monthReport = e ? 1 : 0
                      }
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="奖罚依据"
                  prop="rewardPunishmentBasis"
                >
                  <BaseInput
                    v-model="rewardAndPenalty.rewardPunishmentBasis"
                    :max-length="300"
                    type="textarea"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="事实描述"
                  prop="factDescription"
                >
                  <BaseInput
                    v-model="rewardAndPenalty.factDescription"
                    :max-length="300"
                    type="textarea"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="证明材料"
                  prop="fileArrays"
                >
                  <l-table
                    v-if="editModel != 2"
                    business-code="PM04"
                    :upload-arrys.sync="rewardAndPenalty.fileArrays"
                  />
                  <file-link
                    v-else
                    :file-list="rewardAndPenalty.fileArrays"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <!-- 落实情况 -->
        <a-card
          v-show="editModel == 2"
          :bordered="false"
          :style="[{ marginBottom: !checkInfo || !checkInfo.checkNumber ? '50px' : '20px' }]"
        >
          <title-name title="落实情况" />
          <a-form-model
            ref="implementationInfoForm"
            :model="implementationInfo"
            :rules="rules"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="当前奖罚落实金额"
                  prop="nowImplementationAmount"
                >
                  <BaseInputNumber
                    v-model="implementationInfo.nowImplementationAmount"
                    :max="10000000000"
                    :min="0"
                    :formatter="(value) => `${value}元`"
                    :parser="(value) => value.replace('元', '')"
                    placeholder="请输入"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="当前奖罚落实比例"
                  prop="nowImplementationRatio"
                >
                  <BaseInputNumber
                    v-model="implementationInfo.nowImplementationRatio"
                    :max="10000000000"
                    :min="0"
                    :formatter="(value) => `${value}%`"
                    :parser="(value) => value.replace('%', '')"
                    :disabled="editModel == 2"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
          <s-table
            ref="table"
            table-layout="fixed"
            size="default"
            row-key="id"
            :columns="columns"
            :data="loadData"
            :show-pagination="false"
          >
            <template
              slot="fileArrays"
              slot-scope="text, record"
            >
              <file-link :file-list="record.fileArrays" />
            </template>
          </s-table>
        </a-card>
        <!-- 质量检查信息 -->
        <a-card
          v-if="editModel == 2 && checkInfo && checkInfo.checkNumber"
          :bordered="false"
          style="margin-bottom: 50px"
        >
          <a-form-model
            ref="ruleForm2"
            :model="checkInfo"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel == 0 ? {} : rules"
          >
            <div class="mb20">
              <title-name title="质量检查信息" />
              <div>
                <a-row>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="质量检查编号">
                      <BaseInput
                        v-model="checkInfo.checkNumber"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="分项工程">
                      <div
                        v-if="editModel == 2 && !checkInfo.subProject"
                        style="margin-top:-2px"
                      >
                        无
                      </div>
                      <BaseInput
                        v-else
                        v-model="checkInfo.subProject"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="检查结果">
                      <BaseInput
                        v-model="checkInfo.checkResultName"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="检查人">
                      <BaseInput
                        v-model="checkInfo.checkPeople"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="检查时间">
                      <BaseInput
                        v-model="checkInfo.checkTime"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="检查类型">
                      <BaseInput
                        v-model="checkInfo.checkTypeName"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col
                    :xs="24"
                    :sm="12"
                    :md="8"
                    :lg="8"
                  >
                    <a-form-model-item label="检查区域">
                      {{ checkInfo.checkAreaName || '' }}
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-form-model-item
                      label="现场照片"
                      :label-col="{ lg: 2, md: 3, sm: 3 }"
                      :wrapper-col="{ lg: 22, md: 21, sm: 21 }"
                    >
                      <span v-if="editModel == 2 && (!checkInfo.fileArrays || checkInfo.fileArrays.length < 1)">
                        <empty description="暂未上传现场图" />
                      </span>
                      <div v-else>
                        <l-table
                          upload-type="image"
                          :business-code="'QM01'"
                          :disabled="editModel == 2"
                          :edit-model="editModel"
                          :upload-arrys.sync="checkInfo.fileArrays"
                          multiple
                          isUploadImgAndVideo
                        />
                      </div>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row v-if="checkInfo.checkRecords">
                  <a-col :span="24">
                    <a-form-model-item
                      label="检查记录"
                      :label-col="{ lg: 2, md: 3, sm: 3 }"
                      :wrapper-col="{ lg: 22, md: 21, sm: 21 }"
                    >
                      <BaseTextarea
                        v-model="checkInfo.checkRecords"
                        :rows="6"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-form-model>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div
      v-if="!isConsultation"
        class="btn_box page-btn-right-top"
      >
        <!-- 打印 -->
        <BasePrintButton
          v-if="editModel == 2 && (statusCode == '2' || statusCode == '4')"
          :before-print-fn="() => getPritContent('CSCEC8XN-EQ-B31301')"
          class="button_right"
        />
        <a-button
          v-if="editModel == 1 && statusCode === '0'"
          :disabled="loading[0] || loading[1]"
          type="danger"
          class="button_right"
          @click="handleRemove"
        >
          删除草稿
        </a-button>
        <a-button
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 0"
          :loading="loading[0]"
          :disabled="loading[1]"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
        >
          {{ statusCode === '3' ? '保存' : '保存草稿' }}
        </a-button>
        <a-button
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 0"
          :loading="loading[1]"
          :disabled="loading[0]"
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
        >
          提交
        </a-button>
        <a-button
          v-if="checkVisibleInDetail"
          type="primary"
          @click="handleActiveClose"
        >
          关闭
        </a-button>
      </div>
    </div>
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { rewardAndPenalty } from '@/api/quality/quality' // api
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import Selector from '@/components/Select/Selector' // 通用下拉框
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import { getSubcontractor } from '@/api/businessAffairs/sml'
import { pMen } from '@/api/quality/quality' // api
import { getOrganizeUserListQuick } from '@/api/commons'

const columns = [
  {
    title: '落实人员',
    dataIndex: 'implementationPeople',
  },
  {
    title: '落实时间',
    dataIndex: 'implementationTime',
  },
  {
    title: '奖罚凭证',
    dataIndex: 'fileArrays',
    scopedSlots: { customRender: 'fileArrays' },
  },
  {
    title: '本次落实金额（元）',
    width: '170px',
    dataIndex: 'implementationAmount',
  },
  {
    title: '本次落实比例',
    dataIndex: 'implementationRatio',
    customRender(e) {
      return e ? (e * 100).toFixed(2) + '%' : ''
    },
  },
]

export default {
  name:'a'+ Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    SelectSubCompany,
    SelectProject,
    Selector,
    BasePrintButton,
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    this.columns = columns
    return {
      loading: { 0: false, 1: false }, // 加载控件
      editModel: 2, // 操作类型
      rewardAndPenalty: {}, // 奖罚信息表单
      implementationInfo: {}, // 落实信息表单
      projectInfo: {
        projectId: ""
      }, // 项目信息表单
      checkInfo: null, // 检查信息表单
      statusCode: '', // 审批状态
      targetNameArr:[], // 奖罚目标名称数据
      // selectLoading:false, //奖罚目标名称loading
      selectPlaceholder:'请输入/选择',
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.editModel != 0) {
          this.loading[0] = true
          return rewardAndPenalty
            .getDetail({
              id: this.id,
            })
            .then((res) => {
              this.loading[0] = false
              // 转义纳入质量月报字段
              res.data.rewardAndPenalty.monthReportValue = !!res.data.rewardAndPenalty.monthReport
              // 映射业务
              this.statusCode = res.data.statusCode
              this.projectInfo = res.data.projectInfo
              this.checkInfo = res.data.checkInfo
              if(!this.projectInfo.projectId){
                this.projectInfo.projectId = this.projectInfo.branchCompanyId
              }
              let rewardAndPenalty = res.data.rewardAndPenalty
              this.rewardAndPenalty = rewardAndPenalty
              this.implementationInfo = res.data.implementationInfo
              this.implementationInfo.nowImplementationRatio *= 100
              let datas = {
                data: this.implementationInfo.implementationTable,
              }
              this.$nextTick(() => {
                this.init = true
              })
             
              if (rewardAndPenalty) {
                let rewardAndPenaltyTargetId = rewardAndPenalty.rewardAndPenaltyTargetId
                if (!rewardAndPenaltyTargetId) {
                  res.data.rewardAndPenalty.rewardAndPenaltyTargetId = rewardAndPenalty.rewardAndPenaltyTargetName
                }
              }
              if (rewardAndPenalty && rewardAndPenalty.rewardAndPenaltyTargetCategory) {
                let rewardAndPenaltyTargetCategory = rewardAndPenalty.rewardAndPenaltyTargetCategory
                if(rewardAndPenaltyTargetCategory==='621152034787299328'){ //console.log('自有管理人员')
                  this.getOrganizePeoples()
                }else if(rewardAndPenaltyTargetCategory==='621151985709748224'){ //console.log('分包单位人员')
                  this.getMemQuery()
                }else if(rewardAndPenaltyTargetCategory==='621151959516319744'){ //console.log('单位')
                  this.handleGetSubContractor()
                }
              }
              return datas
            })
            .catch((res) => {
              this.loading[0] = false
            })
        }
      },
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        rewardAndPenaltyAmount: [{ required: true, message: '请输入奖罚金额', trigger: 'change' }],
        rewardAndPenaltyCategory: [{ required: true, message: '请选择奖罚类别', trigger: 'change' }],
        rewardAndPenaltyTargetCategory: [{ required: true, message: '请选择奖罚目标类别', trigger: 'change' }],
        rewardAndPenaltyTargetId: [
          { required: true, whitespace: true, message: '请输入/选择奖罚目标名称', trigger: 'change' },
        ],
        rewardPunishmentBasis: [{ required: true, whitespace: true, message: '请输入奖罚依据', trigger: 'change' }],
        factDescription: [{ required: true, whitespace: true, message: '请输入事实描述', trigger: 'change' }],
        fileArrays: [
          {
            type: 'array',
            message: '请上传奖罚依据!',
            trigger: 'blur',
          },
        ],
        init: false,
      }, // 表单校验规则
      targetNameChangeEd: false, // 是否是输入
      issuingUnit: '',
      selectTageCode: '', // 所选是不是项目
      targetCategoryList: [], // 奖罚目标类别
      //获取流程配置值
        processConfig: null,
       //点击提交发送流程配置值
        setProcessConfig: null,
        businessId: null
    }
  },
  watch: {
    // 监听文件实时校验
    'rewardAndPenalty.fileArrays'(e) {
      if (this.editModel != 2 && this.init) {
        this.$nextTick(() => {
          this.$refs.experimentForm?.validateField('fileArrays')
        })
      }
    },
  },
 async mounted() {
    // issuingUnit
    // PD -> orgName - name BC：-> orgName CO -> orgName
    let fgs = ''
    // 公司
    if (this.$userType() === 'CO') {
      fgs = this.$currentPost().orgName
    }
    // 分公司
    if (this.$userType() === 'BC') {
      fgs = this.$currentPost().orgName
    }
    // 项目 
    if (this.$userType() === 'PD') {
      fgs = this.$currentPost().orgName + '-' + this.$currentPost().name
    }
    this.issuingUnit = fgs
    this.$route.meta.title = ['添加质量奖罚', '编辑质量奖罚', '质量奖罚详情'][this.editModel]
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_reward_punishment')
    if (this.editModel == 0) {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  methods: {
    selectOrg(val) {
      if(val&&val.length) {
        this.projectInfo.branchCompanyId = val[val.length - 1].orgId
        this.projectInfo.unitId = val[val.length - 1].orgId
        this.selectTageCode = val[val.length - 1].tageCode
        if (this.selectTageCode !== 'PD') {
          if (this.targetCategoryList.length > 0) {
            this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetCategory', this.targetCategoryList[0].id)
            //this.$set(this.projectInfo, 'projectId',null)
          }
        }
      }
    },
    changeOrg() {
      // 清空 奖罚目标名称
      this.targetNameArr=[]
      this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetId', '')
      this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetName', '')
      if (this.rewardAndPenalty.rewardAndPenaltyTargetCategory) {
        let rewardAndPenaltyTargetCategory = this.rewardAndPenalty.rewardAndPenaltyTargetCategory
        if(rewardAndPenaltyTargetCategory==='621152034787299328'){ //console.log('自有管理人员')
          this.getOrganizePeoples()
        }else if(rewardAndPenaltyTargetCategory==='621151985709748224'){ //console.log('分包单位人员')
          this.getMemQuery()
        }else if(rewardAndPenaltyTargetCategory==='621151959516319744'){ //console.log('分包商单位')
          this.handleGetSubContractor()
        }
      }
    },
    getTargetCategoryList(list) {
      this.targetCategoryList = list || []
      if (list.length > 0) {
        if (this.selectTageCode !== '' && this.selectTageCode !== 'PD') {
          this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetCategory', list[0].id)
        }
      }
    },
    /**
     * 该项目下的所有人
     * 3.若奖励目标类别选择自有管理人员，则奖励目标名称值：该项目下的所有人员；
     * 4.若奖励目标类别选择为分包单位人员，则奖励目标名称值：该项目下分包商的所有人员；
     * 5.若奖励目标类别选择为单位，则奖励目标名称值：该项目下所有的分包商单位；
     */
     handleChange(e){
      this.targetNameArr=[]
      this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetId', '')
      this.$set(this.rewardAndPenalty, 'rewardAndPenaltyTargetName', '')
      if (e && e.id) {
          let rewardAndPenaltyTargetCategory = e.id
          if(rewardAndPenaltyTargetCategory==='621152034787299328'){ //console.log('自有管理人员')
            this.getOrganizePeoples()
          }else if(rewardAndPenaltyTargetCategory==='621151985709748224'){ //console.log('分包单位人员')
            this.getMemQuery()
          }else if(rewardAndPenaltyTargetCategory==='621151959516319744'){ //console.log('单位')
            this.handleGetSubContractor()
          }
        }
    },
    TargetNameFilterOption(input, option) {
      return option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
    },
    TargetNameSelect(value, option) {
      this.rewardAndPenalty.rewardAndPenaltyTargetName = option.componentOptions.children[0]?.text
      this.targetNameChangeEd = false
    },
    TargetNameChange(e) {
      this.targetNameChangeEd = true
    },
    /**
     * 自有管理人员
     */
    getOrganizePeoples(){
      this.selectPlaceholder='加载中……';
      getOrganizeUserListQuick({comOrgId:this.projectInfo.unitId}).then((res) => {
        if(res.code === 200){
          let data = res.data
          // 去掉重复以及employeeId为空的数据
          let obj = {}
          res.data = res.data.reduce((cur, next) => {
            obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
            return cur
          }, [])
          data.forEach((item) => {
            item.text = item.name + (item.postName ? '-' + item.postName : '')
            item.value = item.employeeId || null
          })
          this.targetNameArr = data
        }
        this.selectPlaceholder='请输入/选择';
      }).catch(err=>{
        // this.selectLoading=false;
        this.selectPlaceholder='请输入/选择';
      })
    },
    /**
     * 分包单位人员
     */
     getMemQuery(){
      this.selectPlaceholder='加载中……';
      pMen.getList({ projectId: this.projectInfo.projectId }).then((res) => {
        if(res.code === 200) {
          let data = res.data
          data.forEach((item) => {
            item.text = item.name
            item.value = item.employeeId || null
          })
          this.targetNameArr = data
        }
        this.selectPlaceholder='请输入/选择';
      }).catch(err=>{
        this.selectPlaceholder='请输入/选择';
      })
    },
    /**
     * 单位
     */
    handleGetSubContractor(){
      this.selectPlaceholder='加载中……';
      getSubcontractor({id:this.projectInfo.projectId})
        .then((res) => {
          if (res.code === 200) {
            let data = res.data
            data.forEach((item) => {
              // item.id = item.subContractorId
              item.text = item.name
              item.value = item.subContractorId || null
            })
            this.targetNameArr = data
          }
          this.selectPlaceholder='请输入/选择';
        }).catch(err=>{
        this.selectPlaceholder='请输入/选择';
      })
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return rewardAndPenalty.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        },
      })
    },
    /**
     * 校验奖罚依据
     */
    validator(rule, value, callback) {
      if (value && value.length > 0) {
        callback()
      } else {
        callback(new Error('请上传奖罚依据'))
      }
    },
    /**
     * 提交表单;e{0:保存草稿,1:提交}
     */
    handleSubmit(e) {
      this.setProcessConfig = null;
      if (this.selectTageCode !== '' && this.selectTageCode !== 'PD') {
        if (this.targetCategoryList?.length > 0) {
            this.$set(this.projectInfo, 'projectId',null)
        }
      }
      // 校验项目信息
      if(e == 0 && !this.projectInfo.unitId){
          this.$message.warning('请选择所属单位！')
        return
      }
      if(this.projectInfo.projectId || this.projectInfo.unitId){
        delete this.rules.projectId;
      }
      this.$refs.ruleForm.validate((res) => {
        if (res || e === 0) {
          e === 0 && this.$refs.ruleForm.clearValidate()
          // 校验试验信息
          this.$refs.experimentForm.validate((res) => {
            if (res || e === 0) {
              e === 0 && this.$refs.experimentForm.clearValidate()
              let name = ['create', 'update'][this.editModel] // 动态取得api请求方法
              let rewardAndPenaltyClone = this.$clone(this.rewardAndPenalty)
              let projectInfoClone = this.$clone(this.projectInfo)
              if (this.targetNameChangeEd) {
                rewardAndPenaltyClone.rewardAndPenaltyTargetName = rewardAndPenaltyClone.rewardAndPenaltyTargetId
                rewardAndPenaltyClone.rewardAndPenaltyTargetId = null
              }
              let form = {
                rewardAndPenalty: rewardAndPenaltyClone,
                projectInfo: projectInfoClone,
                statusCode: this.statusCode == 3 && e == 0 ? this.statusCode : e,
                issuingUnit: this.issuingUnit
              }
              // 若为编辑则添加id
              if (this.editModel == 1) {
                form.id = this.id
              }
              // 加载框
              this.loading[e] = true
              this.submitApprovalConfirm(e==1 ? this.processConfig : 6, (flag)=>{
                if(!flag) {
                  this.loading[e] = false
                  return
                }
                rewardAndPenalty[name](form)
                        .then((res) => {
                          // 取消加载框
                          this.loading[e] = false
                          this.$message.success(['保存', '提交'][e] + '成功！')
                          // 关闭当前页
                          if(e*1===1) {
                            //提交时，返回id
                            this.businessId = res.data.id;
                            this.setProcessConfig = this.processConfig;
                            return
                          }else{
                            this.$multiTab.close()
                          }
                        })
                        .catch((res) => {
                          // this.$message.warning(['保存', '提交'][e] + '失败！')
                          // 取消加载框
                          this.loading[e] = false
                        })
              })

            } else {
              this.$message.warning("请填写完所有必填项信息")
            }
          })
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
  /deep/ .ant-select-auto-complete.ant-select .ant-input[disabled]{
        color: rgb(85,85,85,1);
    }
</style>
